package util

import (
	"fmt"
	"strings"
	"strconv"
)

type ParseError struct {
	Index int
	Word string
	Err error
}

func (e *ParseError) String() string  {
	return fmt.Sprintf("pkg parse: error parsing %q as int",e.Word)
}
func Parse(input string)(numbers []int,err error)  {
	defer func() {
		if r:=recover();r!=nil {
			var ok bool 
			err,ok=r.(error)
			if !ok {
				err=fmt.Errorf("pkg: %v",r)
			}
		}
	}()
	fields:=strings.Fields(input)
	numbers=field2numbers(fields)
	return
}

func field2numbers(fields []string)(numbers []int)  {
	if len(fields)==0 {
		panic("no words to parse")
	}
	for idx,filed:=range fields{
		num,err:=strconv.Atoi(filed)
		if err !=nil{
			panic(&ParseError{idx,filed,err})
		}
		numbers=append(numbers,num)
	}
	return
}













